# -*- coding: utf-8 -*-
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, permission_required
from django.shortcuts import redirect, render
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.contrib import messages
from django.utils.decorators import method_decorator
from .models import Message, Relationship
from django.db import transaction
from django.contrib.auth.models import User as AuthUser
from . import dao
# Create your views here.


class UserDetailView(ListView):
    paginate_by = 20
    template_name = 'twitter/user_detail.html'

    def get_queryset(self):
        return Message.objects.filter(user__username=self.kwargs['username']).order_by('-pub_date')

    def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data(**kwargs)
        obj_user = dao.get_user(self.kwargs['username'])
        if obj_user and self.request.user.is_authenticated:
            context['is_following'] = Relationship.objects.filter(
                from_user=self.request.user, to_user=obj_user).exists()
        else:
            context['is_following'] = None
        context['obj_user'] = obj_user
        if self.kwargs['username'] == self.request.user.username:
            context['page_key'] = 'twitter:my'
        else:
            context['page_key'] = 'twitter:user_list'
        return context


class FollowView(View):
    @method_decorator(login_required)
    def post(self, req, username=None):
        username = self.kwargs['username']
        with transaction.atomic():
            to_user = AuthUser.objects.filter(username=username).get()
            relationship = Relationship(from_user=req.user, to_user=to_user)
            relationship.save()
        messages.add_message(req, messages.INFO,
                             'You are following %s' % username)
        url = reverse('twitter:user_detail', kwargs={'username': username})
        return redirect(url)


class UnFollowView(View):
    @method_decorator(login_required)
    def post(self, req, username):
        username = self.kwargs['username']
        with transaction.atomic():
            to_user = AuthUser.objects.filter(username=username).get()
            Relationship.objects.filter(
                from_user=req.user, to_user=to_user).delete()

        messages.add_message(req, messages.INFO,
                             'You are are no longer %s' % username)
        url = reverse('twitter:user_detail', kwargs={'username': username})
        return redirect(url)


class FollowerListView(ListView):
    paginate_by = 20
    template_name = 'twitter/user_followers.html'

    def get_queryset(self):
        return AuthUser.objects.filter(id__in=self.request.user.follower_list.values('from_user_id'))

    def get_context_data(self, **kwargs):
        context = super(FollowerListView, self).get_context_data(**kwargs)
        context['page_key'] = 'twitter:followers'
        return context


class FollowingListView(ListView):
    paginate_by = 20
    template_name = 'twitter/user_following.html'

    def get_queryset(self):
        return AuthUser.objects.filter(id__in=self.request.user.following_list.values('to_user_id'))

    def get_context_data(self, **kwargs):
        context = super(FollowingListView, self).get_context_data(**kwargs)
        context['page_key'] = 'twitter:following'
        return context


class CreateMessageView2(LoginRequiredMixin, TemplateView):
    login_url = ''
    template_name = "twitter/create.html"

    def post(self, req):
        pass


class CreateMessageView(TemplateView):
    template_name = "twitter/create.html"

    def post(self, req):
        content = req.POST['content']
        message = Message(content=content, user=req.user)
        message.save()
        messages.add_message(req, messages.INFO,
                             'Your message has been created')
        url = reverse('twitter:user_detail', kwargs={
                      'username': req.user.username})
        return redirect(url)


class HomeView(View):
    def get(self, req):
        if not req.user.is_authenticated:
            return PublicTimelineView.as_view()(req)
        else:
            return PrivateTimelineView.as_view()(req)


class UserListView(ListView):
    paginate_by = 20
    template_name = 'twitter/user_list.html'
    ordering = '-id'
    model = AuthUser

    def get_context_data(self, **kwargs):
        context = super(UserListView, self).get_context_data(**kwargs)
        context['page_key'] = 'twitter:user_list'
        return context


class PublicTimelineView(ListView):
    paginate_by = 10
    template_name = 'twitter/public_messages.html'
    ordering = '-pub_date'
    model = Message
    # def get_queryset(self):
    #     return Message.objects.order_by('-pub_date')

    def get_context_data(self, **kwargs):
        context = super(PublicTimelineView, self).get_context_data(**kwargs)
        context['page_key'] = 'twitter:public_timeline'
        return context


class PrivateTimelineView(ListView):
    paginate_by = 10
    template_name = 'twitter/private_messages.html'

    def get_queryset(self):
        user = self.request.user
        following = Relationship.objects.filter(from_user=user)
        return Message.objects.filter(user__in=user.following_list.values('to_user_id')).order_by('-pub_date')

    def get_context_data(self, **kwargs):
        context = super(PrivateTimelineView, self).get_context_data(**kwargs)
        context['page_key'] = 'twitter:private_timeline'
        return context
